define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'jstree'], function ($, undefined, Backend, Table, Form, JsTree) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'data/customer.json',
                    add_url: 'customer-edit.html',
                    edit_url: 'customer-edit.html',
                    del_url: 'data/del.json',
                    multi_url: '',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        //该列为复选框字段,如果后台的返回state值将会默认选中
                        { field: 'state', checkbox: true, },
						{ field: 'id', title: '序号', operate: false },
						{ field: 'name', title: '住户姓名' },
						{ field: 'mobile', title: '联系电话'},
						{ field: 'house_no', title: '房间号', operate: false },
						{ field: 'carport_no', title: '车位号', operate: false },
						{ field: 'car_no', title: '车牌号', operate: 'BETWEEN' },
						{ field: 'id_card', title: '身份证号', operate: false },
						{ field: 'sex', title: '性别', operate: false },
						{ field: 'age', title: '年龄', operate: false },
						{
						    field: 'special', title: '特殊身份', operate: false, formatter: function (value, row, index) {
						        var rValue = "";
						        if (value == "社区意见领袖") {
						            rValue = '<a class="btn btn-xs btn-success">' + value + '</a>';
						        } else if (value == "外籍人员") {
						            rValue = '<a class="btn btn-xs btn-danger">' + value + '</a>';
						        } else if (value == "政府官员") {
						            rValue = '<a class="btn btn-xs btn-primary">' + value + '</a>';
						        } else {
						            rValue = '<a class="btn btn-xs btn-success">' + value + '</a>';
						        }
						        return rValue;
						    }
						},
						{
						    field: 'operate', title: __('Operate'), events: Controller.api.events.operate, formatter: function (value, row, index) {
						        var detail = '<a class="btn btn-xs btn-success btn-detail">详情</a> ';
						        return detail + Table.api.formatter.operate.call(this, value, row, index, table);
						    }
						}
                    ],
                ],
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: true,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                detailView: false,
                showExport: false
            });

            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, settings, json, xhr) {

            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            //指定搜索条件
            $(document).on("click", ".btn-singlesearch", function () {
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    return {
                        search: params.search,
                        sort: params.sort,
                        order: params.order,
                        filter: JSON.stringify({ admin_id: 1 }),
                        op: JSON.stringify({ admin_id: '=' }),
                        offset: params.offset,
                        limit: params.limit,
                    };
                };
                table.bootstrapTable('refresh', {});
                Toastr.info("当前执行的是自定义搜索");
                return false;
            });

            //获取选中项
            $(document).on("click", ".btn-selected", function () {
                Layer.alert(JSON.stringify(table.bootstrapTable('getSelections')));
            });

            //启动和暂停按钮
            $(document).on("click", ".btn-start,.btn-pause", function () {
                //在table外不可以使用添加.btn-change的方法
                //只能自己调用Table.api.multi实现
                Table.api.multi("changestatus", 0, table, this);
            });

            //追加
            $(document).on("click", ".btn-append", function add_line() {
                var tbody = table.find('tbody');
                var tr = $('tr', tbody).eq(0).clone();
                tbody.append(tr);
            });

            //移除
            $(document).on("click", ".btn-remove", function add_line() {
                var tbody = table.find('tbody');
                var rows = tbody.find('tr').length - 1;
                if (rows > 0) {
                    table.find('tbody tr:last').remove();
                } else {
                    Toastr.info("至少保留一行");
                };
            });


                $('#jstree2').jstree({
                    'core': {
                        'check_callback': true
                    },
                    'plugins': ['types', 'dnd'],
                    'types': {
                        'default': {
                            'icon': 'fa fa-folder'
                        },
                        'html': {
                            'icon': 'fa fa-file-code-o'
                        },
                        'svg': {
                            'icon': 'fa fa-file-picture-o'
                        },
                        'css': {
                            'icon': 'fa fa-file-code-o'
                        },
                        'img': {
                            'icon': 'fa fa-file-image-o'
                        },
                        'son': {
                            'icon': 'fa fa-file-text-o'
                        }

                    }
                });

        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
            //加载jstree
            $('#jstree3').jstree({
                'core': {
                    'check_callback': true
                },
                'plugins': ['checkbox', 'types', 'dnd'],
                'types': {
                    'default': {
                        'icon': 'fa fa-folder'
                    },
                    'html': {
                        'icon': 'fa fa-file-code-o'
                    },
                    'svg': {
                        'icon': 'fa fa-file-picture-o'
                    },
                    'css': {
                        'icon': 'fa fa-file-code-o'
                    },
                    'img': {
                        'icon': 'fa fa-file-image-o'
                    },
                    'son': {
                        'icon': 'fa fa-file-text-o'
                    }

                }
            });


            $('#jstree4').jstree({
                'core': {
                    'check_callback': true
                },
                'plugins': ['checkbox', 'types', 'dnd'],
                'types': {
                    'default': {
                        'icon': 'fa fa-folder'
                    },
                    'html': {
                        'icon': 'fa fa-file-code-o'
                    },
                    'svg': {
                        'icon': 'fa fa-file-picture-o'
                    },
                    'css': {
                        'icon': 'fa fa-file-code-o'
                    },
                    'img': {
                        'icon': 'fa fa-file-image-o'
                    },
                    'son': {
                        'icon': 'fa fa-file-text-o'
                    }

                }
            });

            //确定房间选择
            $(document).on("click", ".demo2", function () {
                var houses = $.map($("#jstree3").jstree().get_selected(true), function (v, i) { if (v.children.length == 0) { return { text: $.trim(v.text), parents: v.parents }; } });
                $('#tb_houses tbody').find('tr:gt(0)').remove();
                for (i in houses) {
                    var json = houses[i];
                    var address = $.map(json.parents.slice(0, json.parents.length - 2), function (v, i) { var node = $("#jstree3").jstree().get_node(v); if (node) { return $.trim(node.text) } }).reverse().join('-')
                    var tr = $('#tb_houses tbody').find('tr').eq(0).clone();
                    tr.find('span:first').text(address + '-' + json.text);
                    $('#tb_houses').append(tr.show());

                }

                $('#tb_houses1 tbody').find('tr:gt(0)').remove();
                for (i in houses) {
                    var json = houses[i];
                    var address = $.map(json.parents.slice(0, json.parents.length - 2), function (v, i) { var node = $("#jstree3").jstree().get_node(v); if (node) { return $.trim(node.text) } }).reverse().join('-')
                    var tr = $('#tb_houses1 tbody').find('tr').eq(0).clone();
                    tr.find('span:first').text(address + '-' + json.text);
                    $('#tb_houses1').append(tr.show());

                }
                //加载生成的时间控件样式
                $('.datetimepicker').parent().css('position', 'relative');
                $('.datetimepicker').datetimepicker({
                    //format: 'YYYY-MM-DD',
                    icons: {
                        time: 'fa fa-clock-o',
                        date: 'fa fa-calendar',
                        up: 'fa fa-chevron-up',
                        down: 'fa fa-chevron-down',
                        previous: 'fa fa-chevron-left',
                        next: 'fa fa-chevron-right',
                        today: 'fa fa-history',
                        clear: 'fa fa-trash',
                        close: 'fa fa-remove'
                    },
                    showTodayButton: true,
                    showClose: true
                });
            });

            $(document).on('click', '.demo3', function () {
                $('.selecttext').val('1001;1002;1003');
            });

            $(document).on("click", ".fieldlist .append", function () {
                var rel = parseInt($(this).closest("dl").attr("rel")) + 1;
                var name = $(this).closest("dl").data("name");
                $(this).closest("dl").attr("rel", rel);
                $('<dd class="form-inline" style="margin-left:12px;"> <input type="text" name="' + name + '[value][' + rel + ']" class="form-control" value="" size="40" /> <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span></dd>').insertBefore($(this).parent());
            });
            $(document).on("click", ".fieldlist dd .btn-remove", function () {
                $(this).parent().remove();
            });
            //拖拽排序
            require(['dragsort'], function () {
                //绑定拖动排序
                $("dl.fieldlist").dragsort({
                    itemSelector: 'dd',
                    dragSelector: ".btn-dragsort",
                    dragEnd: function () {

                    },
                    placeHolderTemplate: "<dd></dd>"
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                browser: function (value, row, index) {
                    //这里我们直接使用row的数据
                    return '<a class="btn btn-xs btn-browser">' + row.useragent.split(" ")[0] + '</a>';
                },
                custom: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn btn-xs btn-danger btn-change" data-url="example/bootstraptable/change" data-id="' + row.id + '">' + __('Locked') + '</a>';
                },
                operate: function (value, row, index) {
                    //返回字符串加上Table.api.formatter.operate的结果
                    //默认需要按需显示排序/编辑/删除按钮,则需要在Table.api.formatter.operate将table传入
                    //传入了table以后如果edit_url为空则不显示编辑按钮,如果del_url为空则不显显删除按钮
                    return '<a class="btn btn-info btn-xs btn-detail"><i class="fa fa-list"></i> ' + __('Detail') + '</a> '
                            + Table.api.formatter.operate(value, row, index, $("#table"));
                },
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        console.log();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
                browser: {
                    'click .btn-browser': function (e, value, row, index) {
                        e.stopPropagation();
                        Layer.alert("该行数据为: <code>" + JSON.stringify(row) + "</code>");
                    }
                },
                operate: $.extend({
                    'click .btn-detail': function (e, value, row, index) {
                        e.stopPropagation();
                        Backend.api.open('customer-detail.html', '详情');
                    }
                }, Table.api.events.operate)
            }
        }
    };
    return Controller;
});